<?php
// +----------------------------------------------------------------------
// | 海豚PHP框架 [ DolphinPHP ]
// +----------------------------------------------------------------------
// | 版权所有 2016~2017 河源市卓锐科技有限公司 [ http://www.zrthink.com ]
// +----------------------------------------------------------------------
// | 官方网站: http://dolphinphp.com
// +----------------------------------------------------------------------
// | 开源协议 ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------

namespace app\common\model;

use think\Db;
use think\Exception;
use think\Model;
class Duanwei extends Model
{
    // 设置当前模型对应的完整数据表名称
    protected $name = 'qt_duanwei';
    protected $autoWriteTimestamp = true;


    /**
     * 新增段位费
     * @param $engineerId
     * @param $projectId
     * @param $roomId
     */
    public static function DuanweiPrice($engineerId,$projectId,$roomId){
        $duanweiData = self::where(['project_id'=>$projectId])->where("FIND_IN_SET(" . $engineerId . ",engineer_id)")->find();
        if(!empty($duanweiData)){
            $goodsOrder = Db::name('qt_product_order')->where(['room_id' => $roomId, 'order_status' => '0'])->find();
            $goodsData = Db::name('qt_goods')->where(['id'=>$duanweiData['product_id']])->find();
            if (empty($goodsOrder)) {
                //创建订单
                $orderInsert = [
                    'order_no' => c_order_sn('2'),
                    'store_id' => $goodsData['store_id'],
                    'room_id' => $roomId,
                    'engineer_id' => $engineerId,
                    'create_id' => $engineerId,
                    'hand_card_id' => '',
                    'total_price' => $goodsData['price'],
                    'content' => '',
                    'order_status' => '0',
                    'create_time' => time(),
                ];
//                try {
//                    Db::startTrans();
                    $orderId = Db::name('qt_product_order')->insertGetId($orderInsert);
                    $orderInsert['id'] = $orderId;
                    //插入子订单
                    self::saveProductOrderItem(`$goodsData`, $orderInsert,$engineerId);
                    //处理提成记录
                    self::saveCommissionLog($orderId, $roomId);
                    Db::commit();
                    $result['status'] = true;
                    $result['order_id'] = $orderId;
//                } catch (Exception $exception) {
//                    Db::rollback();
//                    $result['status'] = false;
//                    $result['msg'] = '下单失败';
//                }
            } else {
//                try {
//                    Db::startTrans();
                    //插入子订单
                    $itemStatus = self::saveProductOrderItem($goodsData, $goodsOrder,$engineerId);
                    if($itemStatus['status'] == false){
                        $result['status'] = false;
                        $result['msg'] = $itemStatus['msg'];
                    }else{
                        //处理提成记录
                        self::saveCommissionLog($goodsOrder['id'], $goodsOrder['room_id']);
                        //更新总订单金额
                        Db::name('qt_product_order')->where('id', $goodsOrder['id'])->setInc('total_price', $goodsData['price']);
                        Db::commit();
                        $result['status'] = true;
                        $result['order_id'] = $goodsOrder['id'];
                    }
//                } catch (Exception $exception) {
//                    Db::rollback();
//                }
            }
        }

    }


    /**
     * 写入子订单
     * @param $goodsRes    提交的商品数组
     * @param $orderId     商品订单ID
     * @param $userInfo    用户详情
     * @param $saleId      技师ID
     */
    public static function saveProductOrderItem($goodsData, $orderData, $engineerId)
    {
        $orderData = Db::name('qt_product_order')
            ->field('o.id,o.room_id,o.hand_card_id,hc.type as hand_type')
            ->alias('o')
            ->leftJoin('qt_hand_card hc', 'hc.id = o.hand_card_id')
            ->where('o.id', $orderData['id'])
            ->find();
        if ($orderData['hand_type'] != null) {
            //判断手牌最大商品数量
            $handCardGoodsNumber = Db::name('qt_hand_goods')
                ->where(['product_id' => $goodsData['id'], 'store_id' => $orderData['store_id']])
                ->where("FIND_IN_SET(" . $orderData['hand_type'] . ",type)")
                ->value('number');
            if ($handCardGoodsNumber != null) {
                //判断商品是否超出数量
                $number = Db::name('qt_product_order_item')->where(['order_id' => $goodsData['id'], 'goods_id' => $goodsData['id']])->count();
                if (($number + 1) > $handCardGoodsNumber) {
                    return ['msg' => '超出最大商品数量', 'status' => false];
                }
            }
        }
        $roomId = $orderData['room_id'];
        $insert['order_id'] = $orderData['id'];
        $insert['room_id'] = $roomId;
        $insert['store_id'] = $goodsData['store_id'];
        $insert['hand_card_id'] = '';
        $insert['goods_id'] = $goodsData['id'];
        $insert['goods_name'] = $goodsData['name'];
        $insert['goods_price'] = $goodsData['price'];
        $insert['goods_num'] = '1';
        $insert['goods_total_price'] = $goodsData['price'];
        $insert['create_time'] = time();
        $insert['sale_id'] = $engineerId;
        $insert['create_id'] = $engineerId;
        $insert['business_type'] = 5;
        $insert['commission'] = $goodsData['engineer_rate'];
        $insert['receiver'] = 0;
        Db::name('qt_product_order_item')->insert($insert);
        $secData = Db::name('qt_product_order_item')->where(['order_id' => $orderData['id']])->select();
        foreach ($secData as $key => $value) {
            //插入订单详情表
            $orderDetailInsert = [
                'store_id' => $goodsData['store_id'],
                'room_id' => $orderData['room_id'],
                'engineer_id' => '',
                'hand_card_id' => '',
                'check_out_id' => '',
                'project_id' => $value['goods_id'],
                'order_goods_id' => $value['id'],
                'create_user_id' => $engineerId,
                'order_type' => '2',
                'create_time' => time(),
            ];
            Db::name('qt_order_detail')->insert($orderDetailInsert);
        }
        //商品减库存
        $goodsProduct = Db::name('qt_goods_product')->where(['goods_id' => $goodsData['id']])->find();
        //有关联库存减库存
        if (!empty($goodsProduct)) {
            $stockData = json_decode($goodsProduct['product_data'], true);
            foreach ($stockData as $k => $v) {
                //[{"product_id":46,"number":"2","name":"果粒橙","unit":"瓶"}]
                $productData = Db::name('qt_product')->where(['id' => $v['product_id']])->find();
                //dump($productData);die;
                if ($productData != null) {
                    $decNumber = bcmul($value['goods_num'], $v['number']);
                    $afterNumber = bcsub($productData['stock'], $decNumber);
                    try {
                        Db::startTrans();
                        //减库存
                        Db::name('qt_product')->where(['id' => $v['product_id']])->setDec('stock', $decNumber);
                        //插入记录
                        $insert = [
                            'product_id' => $v['product_id'],
                            'store_id' => $productData['store_id'],
                            'before' => $productData['stock'],
                            'amount' => $decNumber,
                            'after' => $afterNumber,
                            'type' => '1',
                            'acter' => $engineerId,
                            'source' => '2',
                            'relation_id' => $value['id'],
                            'create_time' => time(),
                        ];
                        Db::name('qt_product_stock_log')->insert($insert);
                        Db::commit();
                    } catch (Exception $exception) {
                        Db::rollback();
                    }
                }
            }
            return ['msg' => '添加子订单成功', 'status' => true];
        }
        return ['msg' => '添加子订单成功', 'status' => true];
    }


    /**
     * 写提成记录表
     *
     * @param $order_id      商品订单ID
     * @param $room_id       房间ID
     */
    public static function saveCommissionLog($order_id, $room_id)
    {
        $goods_item = Db::name('qt_product_order_item')
            ->where('order_id', $order_id)->select();
        if (!empty($goods_item)) {
            $insert = [];
            foreach ($goods_item as $key => $value) {
                $checkFind = Db::name('qt_commission_log')->where(['order_project_id'=>$value['id'],'type'=>'2'])->find();
                if(empty($checkFind)){
                    $userGroup = Db::name('qt_users')->where(['id'=>$value['sale_id']])->value('group');
                    if($userGroup != null && $userGroup == '1'){
                        $userId = $value['sale_id'];
                    }else{
                        $userId = 0;
                    }
                    $insert[] = [
                        'store_id' => $value['store_id'],
                        'cashier_id' => !empty($value['sale_id']) ? $value['sale_id'] : 0,
                        'user_id' => $userId,
                        'room_id' => $room_id,
                        'money' => $value['goods_price'],
                        'commission' => $value['commission'],
                        'receiver' => $value['receiver'],
                        'product_id' => $value['goods_id'],
                        'type' => '2',
                        'created_time' => time(),
                        'is_pay' => '1',
                        'order_project_id' => $value['id'],
                    ];
                }
            }
            Db::name('qt_commission_log')->insertAll($insert);

        }
    }


    /**
     * 取消订单删除段位费
     * @param $orderGoodsID
     */
    public static function delDuanweiPrice($orderGoodsID){
        $order_item = Db::name('qt_product_order_item')
            ->alias('oi')
            ->field([
                'oi.id',
                'oi.goods_name',
                'oi.goods_id',
                'oi.goods_num',
                'oi.goods_total_price',
                'po.room_id',
                'po.engineer_id',
                'r.name as room_name',
                'oi.create_id',
                'oi.sale_id'
            ])
            ->leftJoin('qt_product_order po','po.id=oi.order_id')
            ->leftJoin('qt_room r','po.room_id=r.id')
            ->where('oi.id',$orderGoodsID)
            ->find();
        $text = '房间  '.$order_item['room_name']. '  '.$order_item['goods_name'] . '    数量    '.$order_item['goods_num'] . ' 退单';
//        try{
//            Db::startTrans();
            //更新订单详情状态
            Db::name('qt_order_detail')->where('order_goods_id',$orderGoodsID)->update(['status'=>'2']);
            //更新商品订单信息
            Db::name('qt_product_order_item')->where('id',$orderGoodsID)->update(['status'=>'2']);
            //删除提成记录
            Db::name('qt_commission_log')->where(['order_project_id'=>$orderGoodsID])->delete();
            //增加库存记录
            $stockModel = new ProductOrder();
            $stockModel::stockInc($order_item['goods_id'],$order_item['goods_num'],$order_item['id'],['id'=>$order_item['sale_id']]);
            Db::name('qt_send_voice_msg')->insert(['content' => $text, 'type' => 1,'create_time'=>time(),'voice_type'=>2]);
            Db::commit();
//        }catch (Exception $exception){
//            Db::rollback();
//        }
    }


}